#!usr/bin/env python3
from flask import render_template,redirect,url_for,abort,flash
from . import admin as adminBP #导入蓝本
from flask_login import login_required,current_user
from config import getLang #获取语言包的函数 getLang(key,args) 
from app.decorators import admin_required
from app.main.forms import EditProfileForm,EditProfileAdminForm,CommentsForm
from app.models import commit,User,Role
from app.utils import viewUtil

@adminBP.route('/admin_entry/<string:token>')
@login_required
@admin_required
def admin(token):	
	if not current_user.check_token(token):
		abort(404)
	return redirect(url_for('admin.user_admin'))

@adminBP.route('/admin_user')
def user_admin():
	#query = User.query.filter(User.username.ilike('%ca%')) #模糊查询的例子
	query = User.query.order_by(User.member_since.desc())
	print("..... user_admin",query.count())	
	pagination = viewUtil.getPagination(query)
	users = pagination.items
	return render_template('admin/user_admin.html',pagination=pagination,users=users)

@adminBP.route('/admin_post')
def post_admin(): 
	return render_template('admin/post_admin.html')

	
@adminBP.route('/admin_comments')
def comments_admin(): 
	return render_template('admin/comments_admin.html')

@adminBP.route("/edit-profile-admin/<int:id>",methods=['GET','POST'])
@login_required
@admin_required
def editProfileAdmin(id): #管理员编辑资料的页面(这个是管理员用户的资料)
	user=User.query.get_or_404(id)
	form = EditProfileAdminForm(user=user)
	if form.validate_on_submit():
		user.email = form.email.data
		user.username = form.username.data
		user.role = Role.query.get(form.role.data)
		user.name = form.name.data
		user.location = form.location.data
		user.about_me = form.about_me.data
		user.confirmed = form.confirmed.data
		commit([user])
		flash(getLang('adminModifyOk',user.username))
		return redirect(url_for('main.user',username=current_user.username))
	form.email.data = user.email
	form.username.data = user.username
	form.role.data = user.role_id
	form.name.data = user.name
	form.location.data = user.location
	form.about_me.data = user.about_me
	form.confirmed.data = user.confirmed
	return render_template("admin/user_profile.html",form=form,user=user)


@adminBP.before_request
def request_before(): #每次请求蓝本的时候检测是否合法用户		
	pass	
	#if not current_user.is_authenticated or not current_user.is_admin():		
		#abort(404)
	
		